package com.huitone.gddw.service.impl.monitoring;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;


import com.huitone.gddw.dao.entity.AlarmReceiveUser;


import com.huitone.gddw.dao.entity.ObjItem;
import com.huitone.gddw.dao.entity.ObjItemProperty;
import com.huitone.gddw.dao.entity.ObjectManagement;
import com.huitone.gddw.dao.entity.OracleItem;
import com.huitone.gddw.dao.entity.Racinfo;
import com.huitone.gddw.dao.entity.Racstatus;

import com.huitone.gddw.dao.entity.ReturnedValue;
import com.huitone.gddw.dao.entity.SpaceTab;
import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.monitoring.ObjectItemDao;
import com.huitone.gddw.service.OracleItemService;
import com.huitone.gddw.utils.MonitoringResult;

import com.huitone.gddw.utils.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 保存、查找oracle监控数据service实现类
 * @author lipengfei
 *
 */
@Service("oracleService")
public class OracleItemServiceImpl implements OracleItemService {
	
	private final static Logger LOGGER = Logger.getLogger(OracleItemServiceImpl.class);
	
	@Resource
	ObjectItemDao  objDao;
	@Override
	public MonitoringResult<Map<String, Object>> loadOracle(ReturnedValue returnedValue) {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
								
		//用于存放对象的集合
		List<Racinfo> racinfoList = new ArrayList<Racinfo>();
		List<Racstatus> racstatusList = new ArrayList<Racstatus>();
		List<SpaceTab> spaceList = new ArrayList<SpaceTab>();
		List<OracleItem> oracleList = new ArrayList<OracleItem>();
		//用于存放返回数据的map
		Map<String, Object> oracleMap= new HashMap<>();
				
		//传入页码，在数据库全部对象表中查找oracle类型的数据
		Map<String, String> map = new HashMap<>();
		map.put("objType", "rac");
		List<ObjectManagement> objList = objDao.selectObjName(map);
		for(ObjectManagement obj:objList){
			if(obj !=null){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "racinfo");
				ObjItem racinfoItem = objDao.selectObjItemByItemName(objmap);
				System.out.println(racinfoItem);
				if(racinfoItem!=null){
					List<Map<String, String>> proList = objDao.selectValue(racinfoItem.getItemId());
					Racinfo racinfo = new Racinfo();
					for(Map<String, String> pro:proList){
						if(pro.get("KEY").equals("ver")){
							racinfo.setVer(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("nodes")){
							racinfo.setNodes(StringUtils.strToInteger(pro.get("VALUE")));
						}else if(pro.get("KEY").equals("scanip")){
							racinfo.setScanip(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("status")){
							racinfo.setStatus(StringUtils.strToInteger(pro.get("VALUE")));
							
						}
					}
					racinfo.setAlarmCount(objDao.getNowExcptionCount(objmap));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(objmap);
					if(user!=null){
						racinfo.setUser(user.getReceiveUser());
						racinfo.setPhone(user.getPhone());
						racinfo.setEmail(user.getEmail());
					}
					racinfoList.add(racinfo);
				}else{
					Racinfo racinfo = new Racinfo();
					racinfo.setAlarmCount(objDao.getNowExcptionCount(objmap));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(objmap);
					if(user!=null){
						racinfo.setUser(user.getReceiveUser());
						racinfo.setPhone(user.getPhone());
						racinfo.setEmail(user.getEmail());
					}
					racinfoList.add(racinfo);
				}
				
				objmap.put("itemName", "racstatus");
				ObjItem racstatusItem = objDao.selectObjItemByItemName(objmap);
				if(racstatusItem!=null){
					List<Map<String, String>> proList = objDao.selectValue(racstatusItem.getItemId());
					Racstatus racstatus = new Racstatus();
					for(Map<String, String> pro:proList){
						if(pro.get("KEY").equals("name")){
							racstatus.setRacName(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("type")){
							racstatus.setRacType(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("taget")){
							racstatus.setRacAim(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("state")){
							racstatus.setRacStutas(pro.get("VALUE"));
						}else if(pro.get("KEY").equals("host")){
							racstatus.setRacFrom(pro.get("VALUE"));
						}
					}
					racstatusList.add(racstatus);
				}else{
					Racstatus racstatus = new Racstatus();
					racstatusList.add(racstatus);
				}
				
				objmap.put("itemType", "space");
				List<ObjItem> spaceItemList = objDao.selectObjItemByType(objmap);
				for(ObjItem spaceItem:spaceItemList){
					if(spaceItem!=null){
						List<Map<String, String>> proList = objDao.selectValue(spaceItem.getItemId());
						SpaceTab space = new SpaceTab();
						for(Map<String, String> pro:proList){
							if(pro.get("KEY").equals("spacesize")){
								space.setTabSize(StringUtils.strToDouble(pro.get("VALUE")));
							}else if(pro.get("KEY").equals("spaceuse")){
								space.setTabUseSize(StringUtils.strToDouble(pro.get("VALUE")));
							}else if(pro.get("KEY").equals("spacerate")){
								space.setTabUsage(StringUtils.strToDouble(pro.get("VALUE")));
							}else if(pro.get("KEY").equals("filename")){
								space.setTabFileName(pro.get("VALUE"));
							}
						}
						space.setTabName(spaceItem.getItemName());
						spaceList.add(space);
					}else{
						SpaceTab space = new SpaceTab();
						spaceList.add(space);
					}
				}
				
				objmap.put("itemType", "sql");
				List<ObjItem> sqlList = objDao.selectObjItemByType(objmap);
				for(ObjItem sqlItem:sqlList){
					if(sqlItem!=null){
						List<Map<String, String>> proList = objDao.selectValue(sqlItem.getItemId());
						OracleItem oracle = new OracleItem();
						for(Map<String, String> pro:proList){
							if(pro.get("KEY").equals("sql")){
								oracle.setSqlContent(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("status")){
								oracle.setSqlStatus(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("loadtime")){
								oracle.setSqlLoadTime(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("exctime")){
								oracle.setSqlExecuteTime(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("cpu")){
								oracle.setSqlConsumeCpu(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("addr")){
								oracle.setSqlAddress(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("dbuser")){
								oracle.setSqlDatebaseName(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("osuser")){
								oracle.setSqlOsName(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("Ter")){
								oracle.setSqlTerminalName(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("sid")){
								oracle.setSqlSid(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("serial")){
								oracle.setSqlSerial(pro.get("VALUE"));
							}else if(pro.get("KEY").equals("pid")){
								oracle.setSqlThredId(pro.get("VALUE"));
							}
						}
						oracleList.add(oracle);
					}else{
						OracleItem oracle = new OracleItem();
						oracleList.add(oracle);
					}
				}
				result.setStatus(0);
				result.setMsg("oracle监控信息加载成功");
			}else{
				result.setMsg("没有获取到后台数据");		
			}
		oracleMap.put("oracleId", obj.getObjId());
		}
		System.out.println(racinfoList);		
		oracleMap.put("racinfo", racinfoList);
		oracleMap.put("racstatus", racstatusList);
		oracleMap.put("space", spaceList);
		oracleMap.put("sql", oracleList);
						
		//对数据结果进行包装传送
		result.setData(oracleMap);
		return result;
		
	}
	@Override
	public MonitoringResult<Map<String, Object>> showIndex(ReturnedValue value) {
		// TODO Auto-generated method stub
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
				
		
		//存放参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", value.getHostId());
		//获取指标的名称和告警接受人
		List<ObjItemProperty> indexnamelist = new ArrayList<ObjItemProperty>();
		List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(value.getHostId());
				
		List<ObjItem> objItemlist = objDao.selectObjItemById(map);
		if(!objItemlist.isEmpty()){
			for(ObjItem objItem:objItemlist){
				List<ObjItemProperty> indexname = objDao.getIndexName(objItem.getItemId());
				indexnamelist.addAll(indexname);
			}
			result.setStatus(0);
			result.setMsg("主机监控指标名称获取成功,告警接收人获取成功");
		}else{
			result.setMsg("没有获取到指标或者指标信息都已添加");
		}
		resultMap.put("indexnames", indexnamelist);
		resultMap.put("alarmusers", alarmUserList);
		result.setData(resultMap);
		return result;
	
	}
	@Override
	public MonitoringResult<OracleItem> save(ReturnedValue value) {
		MonitoringResult<OracleItem> result = new MonitoringResult<OracleItem>();
		try {
			if(value.getIndex()!=null && value.getAlarmRecUser()!=null){
				JSONArray indexja =JSONArray.fromObject(URLDecoder.decode(value.getIndex(),"UTF-8")); 
				JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
					for(int i = 0;i< indexja.size();i++){
						JSONObject indexjb = indexja.getJSONObject(i);
								if(!indexjb.getString("alarmLevel").isEmpty()){
									//保存指标信息
									ObjItemProperty objItemProperty = new ObjItemProperty();
									objItemProperty.setKeyNameCn(indexjb.getString("indexName"));
									objItemProperty.setKeyId(indexjb.getString("keyId"));
//									if(!indexjb.getString("quantity").isEmpty()){
//										objItemProperty.setQuantity(StringUtils.strToDouble(indexjb.getString("quantity")));
//									}
//									objItemProperty.setIndexUnit(indexjb.getString("unit"));
									objDao.updateIndex(objItemProperty);
									//保存告警信息
									Trigger trigger = new Trigger();
									String triggerId = StringUtils.uuid();
									trigger.setTriggerId(triggerId);
									trigger.setItemId(objDao.selectItemIdByKeyId(indexjb.getString("keyId")));
									trigger.setKeyId(indexjb.getString("keyId"));
									if(!indexjb.getString("upperLimit").isEmpty()){
										trigger.setUpperLimit(StringUtils.strToDouble(indexjb.getString("upperLimit")));
									}
									if(!indexjb.getString("lowerLimit").isEmpty()){
										trigger.setLowerLimit(StringUtils.strToDouble(indexjb.getString("lowerLimit")));
										
									}
//									trigger.setAlarmLevel(StringUtils.strToInteger(indexjb.getString("alarmLevel")));
//									trigger.setSustainTime(indexjb.getString("sustainTime"));
									trigger.setIndexDesc(indexjb.getString("indexDesc"));
									objDao.saveAlarm(trigger);
									//保存告警接受人
									for(int j = 0;j<alarmja.size();j++){
										JSONObject alarmjb = alarmja.getJSONObject(j);
										AlarmReceiveUser user = new AlarmReceiveUser();
										user.setRceId(alarmjb.getString("rceId"));
										user.setObjId(value.getHostId());
										user.setReceiveUser(alarmjb.getString("receiveUser"));
										user.setPhone(alarmjb.getString("phone"));
										user.setEmail(alarmjb.getString("email"));
										user.setUserType(alarmjb.getString("userType"));
										user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
										
										user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
										
										user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
										
										objDao.updateUser(user);
									}
									
							}else{
								result.setMsg("必须添加告警信息");
								return result;
							}
						}
					result.setStatus(0);
					result.setMsg("保存成功");
					return result;

				}else{
					result.setMsg("监控指标或接收人不能为空,保存失败");
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.info("保存出错"+e);
			result.setMsg("保存失败");
		}
		return result;
		
	}

//	@SuppressWarnings("null")
//	@Override
//	public MonitoringResult<Map<String, Object>> updata(ReturnedValue value) {
//		//用于传递数据结果的方法
//		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
//		//存放参数
//		Map<String, String> map = new HashMap<>();
//		map.put("objId", value.getHostId());
//		//用于存储数据结果map
//		Map<String, Object> mainMap = new HashMap<>();
//		//存放指标的集合
//		List<Index> indexList = new ArrayList<Index>();
//		//存放告警接受人的集合
//		List<AlarmReceiveUser> userList =new ArrayList<AlarmReceiveUser>();
//		Index index = new Index();
//		ObjectManagement obj = objDao.selectObjById(map);
//		if(obj!=null){
//			List<ObjItem> objItemList = objDao.selectAllObjItem(map);
//				for(ObjItem objItem:objItemList){
//					if(objItem !=null){
//							List<ObjItemProperty> objProperty = objDao.selectProperty(objItem.getItemId());
//							if(objProperty!=null){
//								for(ObjItemProperty itemPro:objProperty){
//									map.put("itemId", objItem.getItemId());
//									map.put("keyId", itemPro.getKeyId());
//									Trigger trigger = objDao.selectAlarm(map);
//									
//										index.setIndexName(itemPro.getKeyName());
//										index.setQuantity(itemPro.getQuantity());
//										index.setUnit(itemPro.getIndexUnit());
//										index.setAlarmLevel(StringUtils.intToString(trigger.getAlarmLevel()));
//										index.setUpperLimit(trigger.getUpperLimit());
//										index.setLowerLimit(trigger.getLowerLimit());
//										index.setSustainTime(trigger.getSustainTime());
//										indexList.add(index);
//										List<AlarmReceiveUser> recList = objDao.selectAlarmReceiveUser(trigger.getTriggerId());
//										for(AlarmReceiveUser rec:recList){
//											if(userList!=null){
//												for(AlarmReceiveUser user:userList){
//													if(!(user.getRceId().equals(rec.getRceId()))){
//														userList.add(rec);
//													}
//												}
//											}else{
//												userList.add(rec);
//											}
//										}
//									}
//								
//							}else{
//								MonitoringUtils.MonitoringException("该项还没添加指标监控");
//							}
//				}else{
//					MonitoringUtils.MonitoringException("该项还没添加指标监控");
//				}
//			}		
//			result.setStatus(0);
//			result.setMsg("redis监控指标信息获取成功");
//		}else{
//			MonitoringUtils.MonitoringException("该oracle不存在");
//		}
//		mainMap.put("index", indexList);
//		mainMap.put("receiver", userList);
//		result.setData(mainMap);
//		return result;
//				
//	}

	
}
